<script setup lang="ts">

import { QueryObject } from '@/api/helper/utils'

defineProps(['disabled'])
const accountName = defineModel('accountName', {
  type: String,
  default: '',
})
const accountUuid = defineModel()

const accountList = ref([])

const filterName = ref('name')

const conditions = [
  { name: 'name', label: '账户名', op: 'like' },
  { name: 'phone', label: '手机号', op: 'like' },
  { name: 'company', label: '公司名', op: 'like' },
  { name: 'uuid', label: 'UUID', op: '=' },
]
const placeholder = computed(() => {
  const label = conditions.find(item => item.name === filterName.value)?.label
  return `请输入${label}`
})
function querySearchAsync(queryString: string, cb: (arg: any) => void) {
  const qobj = new QueryObject() as any
  qobj.limit = 50
  qobj.fields = ['name', 'uuid', 'company']
  if (queryString) {
    const { op } = conditions.find(item => item.name === filterName.value)
    qobj.conditions = [
      {
        name: filterName.value,
        op,
        value: op === 'like' ? `%${queryString}%` : queryString,
      },
    ]
  }
  useRequest('QueryAccount', qobj).then((res: any) => {
    accountList.value = res.success ? res.inventories : []
    cb(res.inventories)
  })
}
function handleSelect(item: any) {
  accountUuid.value = item.uuid
}

watch(accountUuid, (val) => {
  if (!val)
    accountName.value = ''
})
watch(filterName, () => {
  accountUuid.value = ''
  accountName.value = ''
})
</script>

<template>
  <el-autocomplete
    v-model="accountName"
    :disabled="disabled"
    :fetch-suggestions="querySearchAsync"
    :placeholder="placeholder"
    :debounce="500"
    value-key="name"
    class="w-full"
    clearable
    @clear="() => accountUuid = ''"
    @select="handleSelect"
  >
    <!-- 条件选择 -->
    <template #prepend>
      <el-select
        v-model="filterName"
        placeholder="请选择"
        class="!w-24"
      >
        <el-option
          v-for="item in conditions"
          :key="item.name"
          :label="item.label"
          :value="item.name"
        />
      </el-select>
    </template>

    <!-- 账户列表 -->
    <template #default="{ item }">
      <p class="h-6">
        账户：{{ item.name }}
      </p>
      <p class="company">
        公司：{{ item.company }}
      </p>
    </template>
  </el-autocomplete>
</template>

<style scoped lang='scss'>

</style>
